<template>
  <div class="pageStyle mg-10 pd-20">
    <div class="searchTable">
      <ElRow class="search-color" :gutter="20">
        <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <span class="search-text">计划名称：</span>
          <ElInput
            v-model="planName"
            @input="spaceInput"
            style="width: 70%"
            placeholder="请输入计划名称"
          />
        </ElCol>
        <!-- <ElCol :xs="24" :sm="12" :md="6" :lg="6" :xl="4">
          <span class="search-text">状态：</span>
          <ElSelect
            v-model="status"
            style="width: 70%"
            placeholder="请选择状态"
            @change="search()"
          >
            <ElOption
              v-for="item in statusData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElCol> -->
        <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <ElButton class="b-r-4" type="primary" @click="debouncedSearch"
            >查询</ElButton
          >
          <ElButton class="b-r-4" @click="resetForm()">重置</ElButton>
        </ElCol>
        <ElCol :xs="24" :sm="12" :md="8" :lg="12" :xl="16" class="t-r">
          <ElButton type="primary" @click="addClick()">添加</ElButton>
        </ElCol>
      </ElRow>
    </div>
    <div
      class="tablePage"
      v-loading="showloading"
      element-loading-text="加载中,请稍后..."
    >
      <div style="padding-top: 20px">
        <ElTable :data="tableData" stripe style="width: 100%" row-key="id">
          <ElTable.TableColumn
            prop="planName"
            label="计划名称"
            align="center"
          />
          <ElTable.TableColumn
            prop="executeType"
            label="执行模式"
            align="center"
            width="100"
          />
          <ElTable.TableColumn
            prop="taskRule"
            label="重复规则"
            align="center"
            show-overflow-tooltip
          />
          <ElTable.TableColumn
            prop="airlineName"
            label="航线名称"
            align="center"
          />
          <ElTable.TableColumn
            prop="taskExecuteFeisouOrDrone"
            label="任务下发"
            align="center"
          />
          <ElTable.TableColumn
            prop="createTime"
            label="创建时间"
            align="center"
            width="120"
          />
          <!-- <ElTable.TableColumn prop="status" label="状态" align="center">
            <template #default="scope">
              <ElSwitch
                v-model="scope.row.status"
                @change="updateStatus(scope.row)"
                style="
                  --el-switch-on-color: #2F69EB;
                  --el-switch-off-color: #C0C4CC;
                "
                active-value="1"
                inactive-value="2"
              />
            </template>
          </ElTable.TableColumn> -->
          <ElTable.TableColumn fixed="right" label="操作" align="center">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click="editItem(scope.row)"
              >
                编辑
              </el-button>

              <el-button
                link
                type="primary"
                size="small"
                @click="delClick(scope.row)"
                >删除</el-button
              >
            </template>
          </ElTable.TableColumn>
        </ElTable>
      </div>
      <div class="pagination">
        <ElPagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 80, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import {
  ElButton,
  ElInput,
  ElTable,
  ElSwitch,
  ElPagination,
  ElSelect,
  ElOption,
  ElMessageBox,
  ElMessage,
  ElRow,
  ElCol,
} from "element-plus";
import { onMounted, ref } from "vue";
import { router } from "#/router";
import { list, deleteId } from "#/api/task/patrolScheme";
import { useDebounceFn } from "@vueuse/core";
const planName = ref("");
const status = ref("");
const showloading = ref(false);
const tableData = ref([]);

const statusData = [
  {
    value: "",
    label: "全部",
  },
  {
    value: "1",
    label: "待执行",
  },
  {
    value: "2",
    label: "执行中",
  },
  {
    value: "3",
    label: "已完成",
  },
  {
    value: "4",
    label: "部分执行",
  },
  {
    value: "5",
    label: "执行失败",
  },
  {
    value: "6",
    label: "已取消",
  },
  {
    value: "7",
    label: "已终止",
  },
];
let currentPage = ref(1);
let pageSize = ref(10);
let total = ref(0);
const dialogVisible = ref();
const spaceInput = (value: string) => {
  // 过滤空格
  planName.value = value.replace(/\s+/g, "");
};
const search = async () => {
  showloading.value = true;
  const params = {
    currentPage: currentPage.value,
    pageSize: pageSize.value,
    planName: planName.value,
    // state: status.value,
  };
  const { data } = await list(params);
  if (data.records.length > 0) {
    tableData.value = data.records;
    total.value = data.total;
  } else {
    tableData.value = [];
    total.value = 0;
  }
  showloading.value = false;
};
const debouncedSearch = useDebounceFn(search, 500);

const resetForm = () => {
  planName.value = "";
  status.value = "";
  currentPage.value = 1;
  search();
};
const handleSizeChange = (val) => {
  pageSize.value = val;
  search();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  search();
};

const addClick = () => {
  router.push({
    name: "PatrolDetail",
  });
};

const editItem = async (row) => {
  try {
    await ElMessageBox.confirm(
      `您即将修改计划【${row.planName}】的时间 / 重复规则！修改后，今日执行时间之前的任务将保留不变，但今日执行时间之后的原任务会被永久删除，并按新规则生成新任务。`,
      "修改确认",
      {
        type: "warning",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            done();
            router.push({
              name: "PatrolDetail",
              query: {
                id: row.id,
              },
            });
          } else {
            done();
          }
        },
      }
    );
  } catch (error) {
    if (error !== "cancel") {
    }
  }
};
// 删除
const delClick = async (row) => {
  try {
    await ElMessageBox.confirm(
      `您即将删除计划【${row.planName}】的时间 / 重复规则！删除后，今日执行时间之前的任务将保留不变，但今日执行时间之后的原任务会被永久删除。`,
      "删除确认",
      {
        type: "warning",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            try {
              await deleteId(row.id);
              done();
            } catch (error) {
              instance.confirmButtonLoading = false;
            }
          } else {
            done();
          }
        },
      }
    );
    ElMessage.success("删除成功");
    search();
  } catch (error) {
    if (error !== "cancel") {
      // 非取消操作才报错
      ElMessage.error(`删除失败: ${error.message || "未知错误"}`);
      console.error("删除计划失败:", error);
    }
  }
};
const updateStatus = async (row) => {
  const params = {
    id: row.id,
    status: row.status,
  };
  // const data = await edit(params);
  // if (data.code == 200) {
  //   ElMessage({
  //     type: 'success',
  //     message: '修改成功',
  //   });
  //   search();
  // } else {
  //   ElMessage({
  //     type: 'error',
  //     message: '修改失败',
  //   });
  // }
};

onMounted(() => {
  search();
});
</script>

<style lang="css" scoped>
.pageStyle {
  background: #fff;
}

.tablePage {
  height: calc(100vh - 180px);
}

.el-table--fit {
  height: calc(100vh - 252px);
}

:deep(.el-table--fit .el-table__inner-wrapper:before) {
  width: 0 !important;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  padding: 20px 20px 0 20px;
}

.pd-20 {
  padding-bottom: 0px;
}
</style>
